//
//  FourthViewController.swift
//  HSMainViewControllerHandler
//
//  Created by haisheng huang on 16/1/11.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import UIKit
import HealthKit

class FourthViewController: UIViewController {
    
    var testView: UIView?

    @IBOutlet weak var showLabel: UILabel!
    @IBOutlet weak var stepCountLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
//        let view1: UIView = UIView()
//        view1.backgroundColor = UIColor.blueColor()
//        let view2: UIView = UIView()
//        view2.backgroundColor = UIColor.greenColor()
//        let view3: UIView = UIView()
//        view3.backgroundColor = UIColor.redColor()
//        
//        let infiniteView = HSScrollView(type: HSScrollViewType.autoInfiniteScroll, frame: CGRectMake(100, 100, 300, 300), views: [view1, view2, view3])
//        
//        self.view.addSubview(infiniteView)

//        self.automaticallyAdjustsScrollViewInsets = false
//        
//        let aiView: HSScrollView = HSScrollView(type: HSScrollViewType.autoInfiniteScroll, frame: CGRectMake(15, 300, UIScreen.mainScreen().bounds.width - 30, 100), views: [UIColor.blueColor(), UIColor.greenColor(), UIColor.redColor()])
//        aiView.layer.borderColor = UIColor.redColor().CGColor
//        aiView.layer.borderWidth = 0.5
//        self.view.addSubview(aiView);
        
        testView = UIView(frame: CGRect(x: 60.0, y: 150.0, width: 300.0, height: 300.0))
        testView?.backgroundColor = UIColor.yellow
        //testView?.alpha = 0.0
        self.view.addSubview(testView!)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    
    class func initStoryboardViewController() -> FourthViewController {
        
        return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FourthViewController") as! FourthViewController
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if #available(iOS 8.0, *) {
            
            let healthManager = HealthManager()
            
            healthManager.authorizeHealthKit({ (success, error) in
                if success {
                    print("HealthKit authorization received.")
                } else {
                    print("HealthKit authorization denied!")
                    if error != nil {
                        print("error:\(error)")
                    }
                }
            })
            
            let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)
            healthManager.readMostRecentSample(sampleType!, completion: { (sample, error) in
                
                if error != nil {
                    print("Error reading height from HealthKit Store: \(error?.localizedDescription)")
                    return;
                }
                
                let quantitySample = sample
                //print("distance walking running quantity sample :\(quantitySample)")
                var distance: Double = 0.0
                for temp in quantitySample! {
                    let d = (temp as! HKQuantitySample).quantity.doubleValue(for: HKUnit.meterUnit(with: HKMetricPrefix.kilo))
                    distance += d
                }
                
                DispatchQueue.main.async(execute: { 
                    self.showLabel.text = String(format: "今天已走的距离为：%.2f公里", distance)
                })
                
                
            })
            
            let stepCountSampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
            healthManager.readMostRecentSample(stepCountSampleType!, completion: {[unowned self] (stepCountSample, error)  in
                if error != nil {
                    print("Error reading height from HealthKit Store: \(error?.localizedDescription)")
                    return;
                }
                
                let quantitySample = stepCountSample
                //print("stepcount quantity sample :\(quantitySample)")
                var stepCountResult = 0
                for sample in quantitySample! {
                    let count = (sample as! HKQuantitySample).quantity.doubleValue(for: HKUnit.count())
                    print("count:\(count)")
                    stepCountResult += Int(count)
                }
                
                print("stepCountResult: \(stepCountResult)")
                DispatchQueue.main.async(execute: { 
                    self.stepCountLabel.text = "今天已走的步数为：\(stepCountResult)步"
                })
                
                
            })
        }
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        
//        UIView.animateWithDuration(1.5, delay: 0.4, options: [.Repeat , .Autoreverse], animations: { () -> Void in
//            self.testView?.center.x += 60.0
//            }, completion: { (finish) -> Void in
//                print("finish")
//            })
        
//        UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: { () -> Void in
//            self.testView?.center.y -= 60
//            self.testView?.alpha = 1.0
//            }) { (finish) -> Void in
//                
//        }
        
        let newView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        newView.backgroundColor = UIColor.blue
        newView.center = (self.testView?.center)!
        
        UIView.transition(with: self.testView!,
            duration: 0.33,
            options: [.curveEaseOut, .transitionFlipFromBottom],
            animations: { () -> Void in
                self.testView?.addSubview(newView)
            }, completion: nil)
        
        
    }

}
